package com.java110.mall.user.cmd.user;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.roleShop.RoleShopDto;
import com.java110.dto.shop.ShopDto;
import com.java110.intf.user.IOrgV1InnerServiceSMO;
import com.java110.intf.user.IRoleShopV1InnerServiceSMO;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

@Java110Cmd(serviceCode = "user.listStaffShops")
public class ListStaffShopsCmd extends Cmd {

    @Autowired
    private IRoleShopV1InnerServiceSMO roleShopV1InnerServiceSMOImpl;

    @Autowired
    private IOrgV1InnerServiceSMO orgV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "staffId", "未包含 员工信息");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        String storeId = context.getReqHeaders().get("store-id");
        Assert.hasLength(storeId, "未包含商户信息");

        RoleShopDto orgShopDto = BeanConvertUtil.covertBean(reqJson, RoleShopDto.class);
        orgShopDto.setStaffId(reqJson.getString("staffId"));
        int count = roleShopV1InnerServiceSMOImpl.queryRoleShopsCount(orgShopDto);
        List<ShopDto> shops = null;
        if (count > 0) {
            List<RoleShopDto> roleShopDtos = roleShopV1InnerServiceSMOImpl.queryRoleShops(orgShopDto);
            shops = BeanConvertUtil.covertBeanList(roleShopDtos, ShopDto.class);
            for (RoleShopDto tmpOrgShopDto : roleShopDtos) {
                for (ShopDto tmpApiShopDataVo : shops) {
                    if (tmpOrgShopDto.getShopId().equals(tmpApiShopDataVo.getShopId())) {
                        tmpApiShopDataVo.setShopName(tmpOrgShopDto.getShopName());
                    }
                }
            }
        } else {
            shops = new ArrayList<>();
        }
        ResultVo resultVo = new ResultVo(1, shops.size(), shops);

        ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);

        context.setResponseEntity(responseEntity);

    }
}
